﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TekaMUD.Engine.Blocks
{

	/// <summary>
	/// Represents a door in game which may have a lock that can be opened by one or more keys.
	/// </summary>
	public class Door : GameObject
	{
		public Door()
		{
			Opened = false;
			Name = "door";			
		}

		public override string LookDescription
		{
			get
			{
				return "It's a solid wooden door reinforced with metal platings. It appears to be very old.";
			}
		}
		public bool Opened { get; set; }

		/// <summary>
		/// List of all key codes allowed to open this door.
		/// </summary>
		private List<Guid> AllowedKeys { get; set; }

		/// <summary>
		/// Door closes automatically.
		/// </summary>
		public bool AutoClose { get; set; }

		/// <summary>
		/// Tries to open the door.
		/// </summary>
		public bool Open(Key[] keys)
		{
			lock (SyncRoot)
			{
				if (AllowedKeys == null)
					return true;

				if (keys == null || keys.Length == 0)
					return false;

				foreach(Key playerKey in keys)
					foreach(Guid lockID in AllowedKeys)
						if(playerKey.CombinationCode.Equals(lockID))
							return (Opened = true);

				return false;
			}
		}

		/// <summary>
		/// Tries to open the door without a key
		/// </summary>
		public bool Open()
		{
			lock (SyncRoot)
			{
				if (RequireKey)
					return false;

				return (Opened = true);
			}
		}

		public bool RequireKey
		{
			get
			{
				lock (SyncRoot)
					return AllowedKeys != null && AllowedKeys.Count > 0;
			}
		}

		public void Close()
		{
			lock (SyncRoot)
			{
				Opened = false;
			}
		}

		/// <summary>
		/// Assigns a new key code to the door.
		/// </summary>
		public void AssignKey(Guid code)
		{
			lock (SyncRoot)
			{
				if (AllowedKeys == null)
					AllowedKeys = new List<Guid>();

				AllowedKeys.Add(code);
			}
		}
	}
}
